		#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <mysql.h>
#include "common.h"

// Hardcoded options
#define def_host_name   "localhost" /* host to connect to (default = localhost) */
#define def_user_name   "pxc"       /* user name (default = your login name) */
#define def_password    "pxc"       /* password (default = none) */
#define def_db_name     "pxcdb"     /* database name */
#define def_port_num    0           /* 0    -> use defautt port */
#define def_socket_name NULL        /* NULL -> use default name */

#define USER_ID         1
#define USER_IP         "72.85.123.66"
#define USER_PORT       "55555"

#define SQLMAX          100
#define CMDMAX			200
#define DMAX            10

int startVM(int user_id, char* user_ip, char* user_port) {
	
	MYSQL     *conn;      /* pointer to connection handler */
	MYSQL_RES *res_set;   /* pointer to result set         */
	char      buff[DMAX]; /* buffer to convert user_id to char */
	
	// convert int to *char
	sprintf(buff, "%d", user_id);
	
	// connect to database
	conn = do_connect(def_host_name, def_user_name, def_password, def_db_name,
                      def_port_num, def_socket_name, 0);

	// get VM location based on IP
	// build the query
	char s_query[SQLMAX] = "SELECT vm_path, vm_ip FROM Mapping WHERE user_id=";
	strcat(s_query, buff);
	// process select query - get VM path and IP from DB
	char *res[2];
	process_query(conn, s_query, "get_path_and_ip", res);
	if(res != NULL) {
		pid_t pid;	

		/* Fork off the parent process */
    	pid = fork();
    	if(pid < 0) exit(EXIT_FAILURE);
    	
		/* Parent job: wait for child to complete VM startup */
        /* and register the instance to the DB               */
    	if(pid > 0) {
			printf("Waiting for VM to startup...\n");
			sleep(5);
			//TODO: check if VM started ok
			printf("VM startup OK!\n");
			// update Instances table in DB
			char i_query[SQLMAX] = "INSERT INTO Instances (user_id, user_ip, user_port) VALUES (";
			strcat(i_query, buff); strcat(i_query, ",");
			strcat(i_query, "\'"); strcat(i_query, user_ip); strcat(i_query, "\',");
			strcat(i_query, "\'"); strcat(i_query, user_port); strcat(i_query, "\')");
			process_query(conn, i_query, NULL, NULL);
			// disconnect from database
			do_disconnect(conn);
      		exit(EXIT_SUCCESS);
    	}

		/* Child job: start VM and comunicate success or failure to the parent */ 
		printf("Starting VM %s\n", res[0]);
		execl("/usr/bin/qemu", "/usr/bin/qemu", "-cdrom", res[0], (char *)NULL);
		// We should never reach this line, so if we do is an error
		//TODO: comunicate error to the parent
		exit(EXIT_FAILURE);
	} 
	do_disconnect(conn);
	exit(EXIT_FAILURE);
}

int setIPtables() {
// Just execute ptables command
}

int stopVM(int user_id) {
//TODO
}

void printHelp() {
	printf("Use as follows:\n");
	printf("vmm startvm -u user_id -ip user_ip -p user_port\n");
	printf("vmm stopvm  -u user_id -ip user_ip\n");
	printf("vmm setiptables\n"); 
}

void main(int argc, char** argv) {

	if(argc == 2) {
		if(strcmp(argv[1], "startvm")==0) {
			startVM(USER_ID, USER_IP, USER_PORT);
		}
		else if(strcmp(argv[1],"stopvm")==0) {
			stopVM(USER_ID);
		}
		else if(strcmp(argv[1],"setiptables")==0) {
			setIPtables();
		}
		else printHelp();
	}
	else printHelp();
}
